﻿using System;
using System.Net;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

namespace Toybox.NicoSharp.Live.LiveGuide
{
	using Extensions;
	using Logger;
	using Utilities;

	/// <summary>
	/// 視聴予約 クラス
	/// </summary>
	public class WatchingReservation
	{

		#region [Static]

		/// <summary>
		/// token 取得用 Regex
		/// </summary>
		protected const string REGEX_WATCHNUM = "TimeshiftActions\\.doRegister\\('.+?','(?<ulck>.*?)'\\)";

		/// <summary>
		/// タイムシフト予約済みリスト取得
		/// </summary>
		/// <param name="cookies"></param>
		/// <returns></returns>
		public static ListResult GetList(CookieCollection cookies = null)
		{
			string url = NicoUrls.LiveApi + "watchingreservation" + "?mode=list";
			try
			{
				string html = NicoWebClient.Get(url, cookies.Coerce());
				return Deserializer.XmlDeserializer<ListResult>(html);
			}
			catch (Exception ex)
			{
				TraceLogger.WriteLine(ex.ToString());
				return null;
			}
		}

		/// <summary>
		/// タイムシフト予約のための token 取得
		/// </summary>
		/// <param name="id"></param>
		/// <param name="cookies"></param>
		/// <returns></returns>
		public static string GetWatchNum(string id, CookieCollection cookies = null)
		{
			string url = NicoUrls.LiveApi + "watchingreservation" + "?mode=watch_num&vid=" + id;
			try
			{
				string html = NicoWebClient.Get(url, cookies.Coerce());
				Match match = Regex.Match(html, REGEX_WATCHNUM);
				return match.Success ? match.Groups["ulck"].Value : null;
			}
			catch (Exception ex)
			{
				TraceLogger.WriteLine(ex.ToString());
				return null;
			}
		}

		/// <summary>
		/// 予約登録
		/// </summary>
		/// <param name="id"></param>
		/// <param name="token"></param>
		/// <param name="cookies"></param>
		/// <returns></returns>
		public static bool PostRegist(string id, string token, CookieCollection cookies = null)
		{
			string data = "mode=regist&vid=" + id + "&token=" + token;
			try
			{
				string html = NicoWebClient.Post(NicoUrls.LiveApi + "watchingreservation", data, cookies.Coerce());
				return html.Contains("予約リストに登録しました");
			}
			catch (Exception ex)
			{
				TraceLogger.WriteLine(ex.ToString());
				return false;
			}
		}

		#endregion [Static]

		#region [SubClass]

		/// <summary>
		/// List 結果クラス
		/// </summary>
		[XmlRoot("nicolive_video_response")]
		public class ListResult : Primitives.AbstractLiveStatus
		{
			/// <summary>
			/// タイムシフト予約リスト
			/// </summary>
			[XmlArrayItem("vid")]
			public string[] timeshift_reserved_list;
		}

		#endregion [SubClass]

	}
}
